from datetime import datetime
from flask import Blueprint, request, current_app, g
from util.result import Result
from models import db, Permission

# 创建权限管理的蓝图
api_bp = Blueprint('permission', __name__)


# 1. 分页查询权限接口
@api_bp.route('/permission', methods=['GET'])
def search_Permission():
    try:
        # 1. 获取分页参数（默认第1页，每页10条）
        page = request.args.get('page', type=int)  # 当前页码
        size = request.args.get('size', type=int)  # 每页条数
        # 页码和条数合法性校验
        if page < 1:
            page = 1
        if size < 1 or size > 100:  # 限制最大每页100条，避免性能问题
            size = 10

        # 2. 获取筛选参数
        kw = request.args.get('kw').strip()  # 名称模糊筛选
        begin = request.args.get('begin',type=str)
        end = request.args.get('end',type=str)
        # 3. 构建查询条件
        query = Permission.query
        if kw:
            query = query.filter(Permission.name.like(f"%{kw}%"))

        # 时间范围筛选（begin 和 end 为时间戳）
        if begin:
            begin=datetime.strptime(begin, '%Y-%m-%d')
            query = query.filter(Permission.created_at >= begin)

        if end:
            end=datetime.strptime(end, '%Y-%m-%d')
            query = query.filter(Permission.created_at <= end)

        # 4. 构建排序条件（默认按创建时间倒序）
        query = query.order_by(Permission.id)

        # 5. 执行分页查询（SQLAlchemy内置分页方法）
        paginated_result = query.paginate(page=page, per_page=size, error_out=False)
        # 获取当前页数据
        permissions = paginated_result.items

        # 6. 格式化返回数据
        result_list = [{
            "id": permission.id,
            "name": permission.name,
            "description": permission.description,
            "created_at": permission.created_at.strftime("%Y-%m-%d %H:%M:%S"),
            "updated_at": permission.updated_at.strftime("%Y-%m-%d %H:%M:%S")
        } for permission in permissions]

        # 7. 构建分页响应体（包含分页元信息，方便前端渲染分页组件）
        page_data = {
            "total": paginated_result.total,  # 总记录数
            "page": page,  # 当前页码
            "size": size,  # 每页条数
            "list": result_list  # 当前页数据列表
        }

        return Result.success("分页查询成功", data=page_data)

    except Exception as e:
        current_app.logger.error(f"权限分页查询异常: {str(e)}")
        return Result.error("分页查询权限失败，请稍后重试")